package com.nihome.entershopinfo.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.request.LoginReq;
import com.nihome.entershopinfo.entity.response.LoginRes;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.utils.DES;
import com.nihome.entershopinfo.utils.IntentAction;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.NetUtil;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.nihome.entershopinfo.utils.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/18.
 */
public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    private Context mContext;
    private User mUser;
    private NetUtil mNetUtil;
    private Gson mGson;
    private EditText userPhone;
    private EditText userPwd;
    private TextView loginBtn;

    private LoadingDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUser = SysApplication.getInstance().getmUser();
        if (mUser != null) {
            Intent intent = new Intent(IntentAction.ACTIVITY_HOME_PAGE);
            startActivity(intent);
            finish();
            return;
        }
        setContentView(R.layout.activity_login);
        SysApplication.getInstance().addActivity(this);
        mContext = this;
        mGson = new Gson();
        mNetUtil = new NetUtil(mContext);
        dialog = new LoadingDialog(mContext);
        userPhone = (EditText) findViewById(R.id.user_phone);
        userPwd = (EditText) findViewById(R.id.user_pwd);
        loginBtn = (TextView) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mNetUtil.isNetConnected()) {
                    Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (check()) login();
            }
        });
    }


    private Boolean check(){
        if (StringUtils.isEmpty(userPhone.getText().toString())) {
            Toast.makeText(mContext, "请填写用户名", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (StringUtils.isEmpty(userPwd.getText().toString())) {
            Toast.makeText(mContext, "请填写密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }



    private void login(){
        dialog.show(getString(R.string.load_text));
        LoginReq loginReq = new LoginReq();
        loginReq.setMobile(userPhone.getText().toString());
        loginReq.setPassword(DES.md32Pwd(userPwd.getText().toString()));
        OkHttpUtils.postString().url(RequestAPI.LOGIN_URL)
                .content(new Gson().toJson(loginReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new LoginResponseCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, e + "");
                        dialog.dismiss();
                        if (e instanceof UnknownHostException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof IOException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onResponse(ResponseBase<LoginRes> response, int id) {
                        dialog.dismiss();
                        Log.e(TAG, "onResponse........");
                        switch (Integer.valueOf(response.getResultCode())) {
                            case Constants.REQ_SUCCESS:
                                formatUser(response.getResult());
                                Toast.makeText(mContext, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(IntentAction.ACTIVITY_HOME_PAGE);
                                startActivity(intent);
                                break;
                            default:
                                Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                                break;
                        }

                    }
                });
    }


    abstract class LoginResponseCallback extends Callback<ResponseBase<LoginRes>>{
        @Override
        public ResponseBase<LoginRes> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<LoginRes>>(){}.getType();
            ResponseBase<LoginRes> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }


    private void formatUser(LoginRes res){
        User user = new User();
        user.setUserId(res.getMarketerId());
        user.setUserName(res.getName());
        user.setMobile(res.getMobile());
        user.cache();
        SysApplication.getInstance().setmUser(user);
    }


}
